<template>
  <div class="system-role-container layout-padding">
    <div class="system-role-padding layout-padding-auto layout-padding-view">
      <div class="m-header">
        <div class="pro-name">
          <el-input
            clearable
            size="small"
            placeholder="请输入项目名称或项目编号"
            v-model="proName"
            :suffix-icon="Search"
          />
        </div>
      </div>

      <div class="table_content">
        <el-table
          ref="table_s_exp"
          :height="activeHeight"
          style="width: 100%"
          :header-cell-style="{ background: '#fafbfc', color: '#333333' }"
          :data="tableDataPro"
        >
          
          <el-table-column
            show-overflow-tooltip
            type="index"
            width="80"
            label="序号"
            align="center"
          />
          <el-table-column
            sortable
            width="180"
            show-overflow-tooltip
            label="项目代号"
            prop="proj_no"
          ></el-table-column>
          <el-table-column
            sortable
            min-width="300"
            show-overflow-tooltip
            label="项目名称"
            prop="proj_name"
          >
          <template  #header>
          <div style="display: flex; align-items: center">
            <div style="margin-right: 5px">项目名称</div>
            <el-popover :width="200" trigger="hover">
              <template #reference>
                <div
                  class="icone"
                  :class="proj_name_data.length == 0 ? '' : 'active'"
                >
                  <el-icon>
                    <Filter />
                  </el-icon>
                </div>
              </template>
              <el-select-v2
               
                :teleported="false"
                size="small"
                style="width: 180px; margin-right: 10px; z-index: 2000"
                clearable
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                :options="proj_name_data_options"
                v-model="proj_name_data"
                placeholder="请输入项目名称"
              >
              </el-select-v2>
            </el-popover>
          </div>
        </template>

        </el-table-column>
          <el-table-column
            width="160"
            label="专业负责人"
            show-overflow-tooltip
            prop="professional_leader"
          >
          <template  #header>
          <div style="display: flex; align-items: center">
            <div style="margin-right: 5px">专业负责人</div>
            <el-popover :width="200" trigger="hover">
              <template #reference>
                <div
                  class="icone"
                  :class="professional_leader_data.length == 0 ? '' : 'active'"
                >
                  <el-icon>
                    <Filter />
                  </el-icon>
                </div>
              </template>
              <el-select
               :filter-method="matchProfessional"
                :teleported="false"
                size="small"
                style="width: 180px; margin-right: 10px; z-index: 2000"
                clearable
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                :options="professional_leader_data_options_PY"
                v-model="professional_leader_data"
                placeholder="请输入名称"
              >
              <el-option
               v-for="(item,index) in professional_leader_data_options_PY"
               :key='index'
               :value='item.value'
               :label='item.label'
              >


              </el-option>
              </el-select>
            </el-popover>
          </div>
        </template>
            <template #default="scope">
              <el-tag
                style="margin-right: 5px"
                v-if="scope.row.professional_leader&&scope.row.professional_leader.length > 0"
             
                
                size="small"
                class="ml-2"
                type="success"
              >
                {{ scope.row.professional_leader || "未指定" }}
              </el-tag>
              <el-tag v-else size="small" class="ml-2" type="danger">
                未指定
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            width="160"
            label="责任组长"
            show-overflow-tooltip
            prop="team_leader"
          >

          <template  #header>
          <div style="display: flex; align-items: center">
            <div style="margin-right: 5px">责任组长</div>
            <el-popover :width="200" trigger="hover">
              <template #reference>
                <div
                  class="icone"
                  :class="team_leader_data.length == 0 ? '' : 'active'"
                >
                  <el-icon>
                    <Filter />
                  </el-icon>
                </div>
              </template>
              <el-select
               :filter-method="matchTeamLeader"
                :teleported="false"
                size="small"
                style="width: 180px; margin-right: 10px; z-index: 2000"
                clearable
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                :options="team_leader_options_PY"
                v-model="team_leader_data"
                placeholder="请输入名称"
              >
              <el-option
               v-for="(item,index) in team_leader_options_PY"
               :key='index'
               :value='item.value'
               :label='item.label'
              >


              </el-option>
              </el-select>
            </el-popover>
          </div>
        </template>

            <template #default="scope">
              <el-tag
                style="margin-right: 5px"
                v-if="scope.row.team_leader&&scope.row.team_leader.length > 0"
                size="small"
                class="ml-2"
                type="success"
              >
                {{ scope.row.team_leader || "未指定" }}
              </el-tag>
              <el-tag v-else size="small" class="ml-2" type="danger">
                未指定
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="项目状态"
            show-overflow-tooltip
            prop="proState"
          >
          
            <template #default="scope">
              <div
                v-if="scope.row.proj_status == '已关闭'"
                style="
                  display: inline-block;
                  height: 12px;
                  width: 12px;
                  background-color: #c1c1c1;
                  border-radius: 100% 100%;
                "
              ></div>
              <div
                v-if="scope.row.proj_status == '运行中'"
                style="
                  display: inline-block;
                  height: 12px;
                  width: 12px;
                  background-color: #67c23a;
                  border-radius: 100% 100%;
                "
              ></div>

              <div
                v-if="scope.row.proj_status == '已删除'"
                style="
                  display: inline-block;
                  height: 12px;
                  width: 12px;
                  background-color: #faad14;
                  border-radius: 100% 100%;
                "
              ></div>

              <span style="font-size: 14px; color: #707070">
                &nbsp;{{ scope.row.proj_status }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
          align="center"
            sortable
            width="120"
            show-overflow-tooltip
            label="实时设备数"
            prop="nowEquipCount"
          ></el-table-column>
          <el-table-column
          align="center"
            sortable
            width="150"
            show-overflow-tooltip
            label="半月新增设备数"
            prop="halfMonthAddEquipCount"
          ></el-table-column>
        
          <el-table-column
              width="100"
            label="设计阶段"
            show-overflow-tooltip
            prop="design_stage"
          ></el-table-column>
        
        </el-table>
      </div>
    </div>

   

    
  </div>
</template>
  
  <script setup name="systemRole">
import { onMounted, ref, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  Search,
  CirclePlus,
  Upload,
  Download,
  Delete,
  Filter,
} from "@element-plus/icons-vue";
import { useProjectStore } from "../../stores/project";
import { storeToRefs } from "pinia";
import {
 
  GetProjectList as getPro,
 
  getOptionLeader,
  getOptionTeam,
 
} from "../../api/projectManage/projectList";
import PinYinMatch from "pinyin-match";
let store = useProjectStore();

let list_filtered = ref([]);


let { projectInfo } = storeToRefs(store);

let proName = ref("");

watch(proName, async () => {
  if (proName.value) {
    let res = await getPro({
      user_token: localStorage.getItem("token"),
      authCode: localStorage.getItem("authCode"),
    });
    res.forEach((item) => {
      if (item.create_time) {
        // 清理日期字符串并转换为标准格式
        item.create_time = item.time = item.create_time.replace(/\D/g, "");
      } else {
        // 如果时间是null，分配一个非常小的值以确保它在排序时排在最后
        item.create_time = -Infinity;
      }
    });

    res.sort((a, b) => {
      // 如果两个元素都不是null，比较它们的日期，将最新的日期排在前面
      return b.create_time - a.create_time;
    });
    let data = JSON.parse(JSON.stringify(res));
    tableDataPro.value = data
      .filter(
        (v) =>
          v.proj_name.toLowerCase().includes(proName.value.toLowerCase()) ||
          v.proj_no.toLowerCase().includes(proName.value.toLowerCase())
      )
      tableDataPro.value = tableDataPro.value.filter(v=>v.proj_status==='运行中')
  
     
  } else {
    getProTable({
        user_token: localStorage.getItem("token"),
        authCode: localStorage.getItem("authCode"),
      },

      proj_name_data.value,
      professional_leader_data.value,
      team_leader_data.value,
    );
  }
});

let matchProfessional = (searchContent) => {
  if (searchContent) {
    let result = [];
    professional_leader_data_options.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      if (matchResult) {
        result.push(item);
      }
    });
 
    professional_leader_data_options_PY.value = result;
  } else {
    professional_leader_data_options_PY.value = professional_leader_data_options.value;
  }
};

let matchTeamLeader = (searchContent) => {
  if (searchContent) {
    let result = [];
    team_leader_options.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      if (matchResult) {
        result.push(item);
      }
    });

    team_leader_options_PY.value = result;
  } else {
    team_leader_options_PY.value = team_leader_options.value;
  }
};


let proj_name_data = ref([])
let proj_name_data_options = ref([])
let professional_leader_data = ref([])
let professional_leader_data_options = ref([])
let professional_leader_data_options_PY = ref([])
let team_leader_data = ref([])
let team_leader_options = ref([])
let team_leader_options_PY  = ref([])

let getProTable = async (data,proj_name=[],professional_leader=[],team_leader=[]) => {
  let res = await getPro(data);
  res.forEach((item) => {
      if (item.create_time) {
        // 清理日期字符串并转换为标准格式
        item.create_time = item.time = item.create_time.replace(/\D/g, "");
      } else {
        // 如果时间是null，分配一个非常小的值以确保它在排序时排在最后
        item.create_time = -Infinity;
      }
    });

    res.sort((a, b) => {
      // 如果两个元素都不是null，比较它们的日期，将最新的日期排在前面
      return b.create_time - a.create_time;
    });

  let ORGdata = res.filter(v=>(!(v.proj_no.includes('test')||v.proj_name.includes('test')
|| v.proj_no.includes('TEST') || v.proj_name.includes('TEST') ||v.proj_name.includes('测试')
|| v.proj_no.includes('测试') ||v.proj_name.includes('虚拟')))
)
  proj_name_data_options.value = getOptionsData(ORGdata, "proj_name");
  professional_leader_data_options.value = (getOptionsData(ORGdata, "professional_leader"))
  professional_leader_data_options_PY.value = professional_leader_data_options.value
  team_leader_options.value = getOptionsData(ORGdata, "team_leader");
  team_leader_options_PY.value = team_leader_options.value
  const filters = {
    proj_name, 
    professional_leader,
    team_leader
  };


  tableDataPro.value = multiFilter(JSON.parse(JSON.stringify(ORGdata)), filters)
  tableDataPro.value = tableDataPro.value.filter(v=>v.proj_status==='运行中')
  return tableDataPro.value;
};

function multiFilter(array, filters) {
  const filterKeys = Object.keys(filters);

  return array.filter((item) => {
    return filterKeys.every((key) => {
      if (!filters[key].length) return true;
      return !!~filters[key].indexOf(item[key]);
    });
  });
}

let getOptionsData = (data, str) => {
  return [...new Set(data.map((v) => v[str]))]
    .filter((v) => {
      if (v) {
        return v;
      }
    })
    .map((v) => {
      return {
        value: v,
        label: v,
      };
    });
};


watch([proj_name_data,professional_leader_data,team_leader_data],()=>{

  getProTable({
        user_token: localStorage.getItem("token"),
        authCode: localStorage.getItem("authCode"),
      },

      proj_name_data.value,
      professional_leader_data.value,
      team_leader_data.value,
    );
})


let personOptions = ref([]);




let tableDataPro = ref([]);



let getOptions = async (data) => {
  let option1 = await getOptionTeam(data);
  let option2 = await getOptionLeader(data);
  userOptionsleader.value = option2;
  optionsNewteam_leader.value = option1;
};



watch(
  projectInfo,
  () => {
    if (projectInfo.value && Object.keys(projectInfo.value).length > 0) {
      getOptions({});
      getProTable({
        user_token: localStorage.getItem("token"),
        authCode: localStorage.getItem("authCode"),
      },

      proj_name_data.value,
      professional_leader_data.value,
      team_leader_data.value,
    );
    }
  },
  { immediate: true }
);




let activeHeight = ref(0);


let userOptionsleader = ref([]);
let optionsNewteam_leader = ref([]);


// 页面加载时
onMounted(() => {
  activeHeight.value =
    document.querySelector(".system-role-padding").clientHeight - 80;
  window.addEventListener("resize", () => {
    activeHeight.value =
      document.querySelector(".system-role-padding").clientHeight - 80;
  });
});
</script>
  
  <style scoped lang="scss">
.m-header {
  display: flex;
  align-items: center;
}
.m-header .pro-name {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.m-header .el-input {
  width: 300px;
}
.m-header .el-button {
  margin-right: 10px;
}

.system-role-container {
  .system-role-padding {
    padding: 15px;
    .el-table {
      flex: 1;
    }
  }
}
.button_footer {
  display: flex;
  flex-direction: row-reverse;
  width: 100%;
}
.table_content {
  margin-top: 20px;
}

::v-deep(.el-table--large .el-table__cell) {
  padding: 6px 0;
}

.table_box {
  padding: 20px 50px;
}

.button_poastion_flex_iem {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
  height: 100%;
}

.backgroun_border {
  // 	::v-deep .el-tabs__header {
  //     margin-top: 39px;
  //   }
}

::v-deep(.el-tabs__item::after) {
  position: absolute;
  content: " ";
  top: 0;
  width: 2px;
  height: 100%;
  background: #eee;
  right: 0;
}


.active {
  color: rgb(24, 144, 255);
}

.icone {
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep(.cell){
  display: flex;
  align-items: center;
}
</style>
  